<template>
    <div class="marketing_lottery_add">
        <el-form label-width="120px" :model="form" :rules="rules" ref="luckyForm">
            <div class="form_content">
                <el-card class="base_card">
                    <template #header>活动设置</template>
                    <el-row>
                        <el-col>
                            <el-form-item label="活动名称" prop="activityName">
                                <el-input
                                    maxlength="20"
                                    v-model.trim="form.activityName"
                                    show-word-limit
                                    placeholder="请输入活动名称，20个字以内"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col>
                            <el-form-item label="活动时间" prop="activityAt">
                                <template v-if="isDisabled">
                                    <div>
                                        <span @mouseover="handleMouseover" @mouseleave="handleMouseleave">
                                            <el-date-picker
                                                type="datetime"
                                                style="width: 47%"
                                                v-model="form.activityAt[0]"
                                                placeholder="开始时间"
                                                :disabled="isDisabled"
                                                :default-time="defaultTime"
                                                :disabled-date="disabledDate" />
                                        </span>
                                        至
                                        <el-date-picker
                                            type="datetime"
                                            style="width: 47%"
                                            v-model="form.activityAt[1]"
                                            placeholder="结束时间"
                                            :default-time="defaultTime"
                                            :disabled-date="disabledBeforeDate" />
                                    </div>
                                </template>
                                <el-date-picker
                                    v-else
                                    v-model="form.activityAt"
                                    type="datetimerange"
                                    range-separator="至"
                                    start-placeholder="开始时间"
                                    end-placeholder="结束时间"
                                    :default-time="defaultTime"
                                    :disabled-date="disabledDate" />
                            </el-form-item>
                        </el-col>
                        <el-col>
                            <el-form-item label="抽奖规则" prop="remark">
                                <el-input
                                    type="textarea"
                                    maxlength="500"
                                    show-word-limit
                                    :rows="4"
                                    v-model.trim="form.remark"
                                    resize="none"
                                    placeholder="请填写抽奖规则，不超过500字"></el-input>
                                <div class="custom-tip">若不填写抽奖规则，则活动页面默认展示活动</div>
                            </el-form-item>
                        </el-col>
                        <el-col>
                            <el-form-item label="抽奖次数" prop="everyDayNum" class="custom-num-item">
                                <div>
                                    每人每天可抽奖
                                    <el-input-number
                                        v-model="form.everyDayNum"
                                        class="custom-number-small"
                                        :precision="0"
                                        :disabled="isDisabled"
                                        :controls="false" />次
                                </div>
                                <div style="margin-top: 16px">
                                    <el-checkbox
                                        v-model="form.perPerson"
                                        :disabled="isDisabled"
                                        @change="handlePerPersonNum"
                                        >每人一共可抽奖</el-checkbox
                                    >
                                    <el-input-number
                                        v-model="form.perPersonNum"
                                        class="custom-number-small"
                                        :precision="0"
                                        :disabled="!form.perPerson || isDisabled"
                                        :controls="false" />次
                                </div>
                            </el-form-item>
                        </el-col>
                        <el-col>
                            <el-form-item label="中奖次数" prop="awardNum">
                                <el-radio-group v-model="form.award" @change="handleAwardNumChange">
                                    <el-radio :label="false">无限制</el-radio>
                                    <el-radio :label="true">
                                        每人中奖<el-input-number
                                            v-model="form.awardNum"
                                            @blur="handleAwardNumBlur"
                                            class="custom-number-small"
                                            :min="form.award ? 1 : 0"
                                            :precision="0"
                                            :disabled="!form.award || isDisabled"
                                            :controls="false" />次
                                    </el-radio>
                                </el-radio-group>
                            </el-form-item>
                        </el-col>
                        <el-col>
                            <el-form-item label="额外抽奖机会" prop="extraRaffleNum" class="activity-name-item">
                                <el-checkbox
                                    v-model="form.extraRaffle"
                                    :disabled="isDisabled"
                                    @change="handleExtraRaffleChange"
                                    >邀请1位新用户，可获得1次抽奖机会</el-checkbox
                                ><span class="custom-tip">（新用户是指未获取手机号的用户。）</span>
                                <div v-if="form.extraRaffle" style="margin-top: 12px">
                                    <el-select
                                        style="width: 90px"
                                        v-model="form.extraRaffleType"
                                        :disabled="isDisabled">
                                        <el-option :value="2" label="每天"></el-option>
                                        <el-option :value="1" label="每人"></el-option>
                                    </el-select>
                                    最多可获得
                                    <el-input-number
                                        :disabled="isDisabled"
                                        v-model="form.extraRaffleNum"
                                        class="custom-number-small"
                                        :min="1"
                                        :precision="0"
                                        :controls="false" />次
                                </div>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-card>
                <el-card class="base_card">
                    <template #header>奖品设置</template>
                    <el-row>
                        <el-col style="margin-bottom: 16px">
                            <!-- todo:disabled -->
                            <el-button
                                type="primary"
                                @click="handlePrizeDialog(null)"
                                :disabled="form.luckDrawAward.length == 7 || isDisabled"
                                >添加奖品</el-button
                            >
                            <span class="custom-tip" style="margin-left: 4px">*最多添加7个</span>
                        </el-col>
                        <!-- todo:表格数据 -->
                        <el-col v-if="form.luckDrawAward.length">
                            <el-table :data="form.luckDrawAward" style="width: 1000px">
                                <el-table-column
                                    v-for="{ prop, ...rest } in luckDrawAwardCol"
                                    :key="prop"
                                    :prop="prop"
                                    v-bind="rest">
                                    <template #default="{ row }">
                                        <template v-if="prop === 'awardType'">{{ getTypeName(row[prop]) }} </template>
                                        <el-image
                                            v-if="prop === 'awardImg'"
                                            style="width: 40px; height: 40px"
                                            :src="getImgSrcObject(row[prop])"
                                            fit="fill"></el-image>
                                        <template v-if="prop === 'awardTotalNum'">
                                            {{
                                                [null, undefined].includes(row.awardTotalNum)
                                                    ? row.awardSurplusNum
                                                    : row.awardTotalNum
                                            }}
                                        </template>
                                        <template v-if="prop === 'operation'">
                                            <el-button
                                                size="small"
                                                :disabled="isDisabled"
                                                @click="handlePrizeDialog(row)"
                                                >编辑</el-button
                                            >
                                            <el-button size="small" :disabled="isDisabled" @click="handleRemove(row)"
                                                >删除</el-button
                                            >
                                        </template>
                                    </template>
                                </el-table-column>
                            </el-table>
                        </el-col>
                        <el-col>
                            <h1>未中奖设置</h1>
                            <el-form-item label="名称" class="not-width-item" prop="noLuckyConfig.awardName">
                                <el-input
                                    v-model="form.noLuckyConfig.awardName"
                                    maxlength="10"
                                    show-word-limit></el-input>
                            </el-form-item>
                            <el-form-item
                                label="图片"
                                class="not-width-item"
                                prop="noLuckyConfig.awardImg"
                                style="position: relative">
                                <!-- todo:校验 -->
                                <ImgUpload
                                    ref="defaultImgRef"
                                    v-model="form.noLuckyConfig.awardImg"
                                    :is-change="true"
                                    :currentImg="getCurrentImg(form?.noLuckyConfig?.awardImg)"
                                    tip-content="建议尺寸200*200，不超过1M，支持jpg、png、jpeg" />
                                <span
                                    style="
                                        color: rgb(255, 107, 0);
                                        top: 55px;
                                        position: absolute;
                                        left: 100px;
                                        cursor: pointer;
                                    "
                                    @click="handleDefault">
                                    <el-icon><RefreshLeft /></el-icon>
                                    恢复默认图
                                </span>
                            </el-form-item>
                        </el-col>
                        <el-col>
                            <h1>转盘设置</h1>
                            <el-form-item label="转盘样式" class="not-width-item" prop="noLuckyConfig.awardName">
                                <el-radio-group v-model="form.styleType" :disabled="isDisabled">
                                    <el-radio :label="1">抽签抽奖</el-radio>
                                    <el-radio :label="2">大转盘</el-radio>
                                </el-radio-group>
                            </el-form-item>
                            <div class="draw-custom-col">
                                <!-- <el-table :data="form.luckDrawTurntable" class="custom-draw-table">
                                <el-table-column
                                    v-for="{ prop, ...rest } in turntableCol"
                                    :key="prop"
                                    :prop="prop"
                                    v-bind="rest">
                                    <template #default="{ row, $index }">
                                        <el-select
                                            :disabled="isDisabled"
                                            style="width: 70%"
                                            v-if="prop === 'awardRelation'"
                                            v-model="row[prop]">
                                            <el-option
                                                v-for="item in drawSelectList"
                                                :value="item.awardRelation"
                                                :label="item.awardName"
                                                :key="item.awardRelation"></el-option>
                                        </el-select>
                                        {{ row.awardImg }}
                                        <el-image
                                            :src="getImgSrcForId(row.awardRelation) || defaultImg"
                                            v-if="prop === 'img'"
                                            style="width: 40px; height: 40px"
                                            fit="fill" />
                                        <el-form-item
                                            label-width="0"
                                            style="width: 90px; margin: 0"
                                            v-if="prop === 'weight'"
                                            :prop="'luckDrawTurntable.' + $index + '.weight'"
                                            :rules="weightRules">
                                            <el-input-number
                                                :disabled="isDisabled"
                                                style="width: 90px"
                                                :min="1"
                                                :max="999"
                                                :precision="0"
                                                :controls="false"
                                                v-model="row.weight"></el-input-number>
                                        </el-form-item>
                                        <template v-if="prop == 'awardProbability'">
                                            {{ getWeight(row.weight || 0) }}
                                        </template>
                                    </template>
                                </el-table-column>
                            </el-table> -->
                                <div class="custom-table">
                                    <div class="custom-table-col">
                                        <div></div>
                                        <div>奖品名称</div>
                                        <div>转盘图片</div>
                                        <div>奖品权重</div>
                                        <div>转到概率</div>
                                    </div>
                                    <draggable
                                        :list="form.luckDrawTurntable"
                                        :options="sortOptions"
                                        handle=".sortable-drag"
                                        style="width: 100%"
                                        :disabled="isDisabled"
                                        item-key="roader">
                                        <template #item="{ element: row, index }">
                                            <div class="custom-table-col-drag">
                                                <div>
                                                    <img
                                                        src="@/assets/imgs/sys/drag-icon.png"
                                                        style="width: 16px"
                                                        alt=""
                                                        class="sortable-drag"
                                                        :class="{ 'sortable-drag-not': isDisabled }" />
                                                </div>
                                                <div>
                                                    <el-select
                                                        :disabled="isDisabled"
                                                        style="width: 70%"
                                                        v-model="row.awardRelation">
                                                        <el-option
                                                            v-for="item in drawSelectList"
                                                            :value="item.awardRelation"
                                                            :label="item.awardName"
                                                            :key="item.awardRelation"></el-option>
                                                    </el-select>
                                                </div>
                                                <div>
                                                    <el-image
                                                        :src="getImgSrcForId(row.awardRelation) || defaultImg"
                                                        style="width: 40px; height: 40px"
                                                        fit="fill" />
                                                </div>
                                                <div>
                                                    <el-form-item
                                                        label-width="0"
                                                        style="width: 90px; margin: 0"
                                                        :prop="'luckDrawTurntable.' + index + '.weight'"
                                                        :rules="weightRules">
                                                        <el-input-number
                                                            :disabled="isDisabled"
                                                            style="width: 90px"
                                                            :min="1"
                                                            :precision="0"
                                                            :controls="false"
                                                            v-model="row.weight"></el-input-number>
                                                    </el-form-item>
                                                </div>
                                                <div>
                                                    {{ getWeight(row.weight || 0) }}
                                                </div>
                                            </div>
                                        </template>
                                    </draggable>
                                </div>
                                <div class="lucky-preview" v-if="form.styleType == 1">
                                    <div class="lucky-preview-list">
                                        <div
                                            class="lucky-preview-list-item"
                                            v-for="(item, index) in luckyList"
                                            :key="item.id">
                                            <el-image
                                                v-if="index !== 4"
                                                style="width: 60px; height: 60px"
                                                :src="getImgSrcForId(item.awardRelation) || defaultImg"
                                                fit="fill">
                                                <template #error>
                                                    <div class="image-slot">
                                                        <el-image
                                                            :src="defaultImg"
                                                            style="width: 40px; height: 40px"
                                                            fit="fill" />
                                                    </div>
                                                </template>
                                            </el-image>
                                            <div class="default-item-box" v-else>抽奖</div>
                                            <el-tooltip
                                                class="box-item"
                                                effect="dark"
                                                :content="getAwardName(item.awardRelation)"
                                                placement="bottom">
                                                <span class="box-item-span">{{
                                                    getAwardName(item.awardRelation)
                                                }}</span>
                                            </el-tooltip>
                                        </div>
                                    </div>
                                    <!-- todo:隐藏 -->
                                    <div class="lucky-preview-bottom" v-if="form.extraRaffle">
                                        <div></div>
                                        <div>
                                            <p>内容邀请新用户，得抽奖机会（0/1）</p>
                                            <p>邀请1名新用户，抽奖机会+1</p>
                                        </div>
                                        <div>去邀请</div>
                                    </div>
                                </div>
                                <div class="lucky-preview-table" v-else>
                                    <div class="lucky-preview-table-list">
                                        <div class="left">
                                            <div
                                                class="lucky-preview-table-list-item circle-left"
                                                v-for="item in leftList"
                                                :key="item.id">
                                                <div class="inner">
                                                    <el-tooltip
                                                        class="box-item"
                                                        effect="dark"
                                                        :content="getAwardName(item.awardRelation)"
                                                        placement="bottom">
                                                        <span class="box-item-span">{{
                                                            getAwardName(item.awardRelation)
                                                        }}</span>
                                                    </el-tooltip>
                                                    <el-image
                                                        style="width: 40px; height: 40px; margin-top: 4px"
                                                        :src="getImgSrcForId(item.awardRelation) || defaultImg"
                                                        fit="fill">
                                                        <template #error>
                                                            <div class="image-slot">
                                                                <el-image
                                                                    :src="defaultImg"
                                                                    style="width: 40px; height: 40px"
                                                                    fit="fill" />
                                                            </div>
                                                        </template>
                                                    </el-image>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="right">
                                            <div
                                                class="lucky-preview-table-list-item circle-right"
                                                v-for="item in rightList"
                                                :key="item.id">
                                                <div class="inner">
                                                    <el-tooltip
                                                        class="box-item"
                                                        effect="dark"
                                                        :content="getAwardName(item.awardRelation)"
                                                        placement="bottom">
                                                        <span class="box-item-span">{{
                                                            getAwardName(item.awardRelation)
                                                        }}</span>
                                                    </el-tooltip>
                                                    <el-image
                                                        style="width: 40px; height: 40px"
                                                        :src="getImgSrcForId(item.awardRelation) || defaultImg"
                                                        fit="fill">
                                                        <template #error>
                                                            <div class="image-slot">
                                                                <el-image
                                                                    :src="defaultImg"
                                                                    style="width: 40px; height: 40px"
                                                                    fit="fill" />
                                                            </div>
                                                        </template>
                                                    </el-image>
                                                </div>
                                            </div>
                                        </div>
                                        <!-- <div
                                        class="lucky-preview-table-list-item"
                                        v-for="(item, index) in form.luckDrawTurntable"
                                        :key="item.id">
                                        <div class="inner">
                                            <el-tooltip
                                                class="box-item"
                                                effect="dark"
                                                :content="getAwardName(item.awardRelation)"
                                                placement="bottom">
                                                <span class="box-item-span">{{
                                                    getAwardName(item.awardRelation)
                                                }}</span>
                                            </el-tooltip>
                                            <el-image
                                                style="width: 40px; height: 40px"
                                                :src="getImgSrcForId(item.awardRelation) || defaultImg"
                                                fit="fill">
                                                <template #error>
                                                    <div class="image-slot">
                                                        <el-image
                                                            :src="defaultImg"
                                                            style="width: 40px; height: 40px"
                                                            fit="fill" />
                                                    </div>
                                                </template>
                                            </el-image>
                                        </div>
                                    </div> -->
                                    </div>
                                    <div class="lucky-preview-table-bottom" v-if="form.extraRaffle">
                                        <div></div>
                                        <div>
                                            <p>内容邀请新用户，得抽奖机会（0/1）</p>
                                            <p>邀请1名新用户，抽奖机会+1</p>
                                        </div>
                                        <div>去邀请</div>
                                    </div>
                                </div>
                            </div>
                        </el-col>
                    </el-row>
                </el-card>
                <el-card class="base_card">
                    <template #header>分享设置</template>
                    <el-row>
                        <el-col>
                            <el-form-item label="文案" prop="shareCopy" class="not-width-item">
                                <el-input v-model="form.shareCopy" maxlength="10" show-word-limit></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col>
                            <el-form-item label="图片" prop="shareImg" class="not-width-item">
                                <ImgUpload
                                    ref="shareImgRef"
                                    v-model="form.shareImg"
                                    :is-change="true"
                                    :currentImg="getCurrentImg(form.shareImg, shareImg)"
                                    tip-content="建议尺寸200*200，不超过1M，支持jpg、png、jpeg" />
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-card>
            </div>
            <div class="form-footer">
                <div>
                    <el-button @click="cancelHandler">取消</el-button>
                    <el-button type="primary" @click="saveHandler">保存</el-button>
                </div>
            </div>
        </el-form>
        <!-- tooltip提示框 -->
        <el-tooltip
            popper-class="custom-tooltip-class"
            v-model:visible="tooltipVisible"
            content="活动已开始不支持编辑"
            placement="top"
            trigger="click"
            virtual-triggering
            :virtual-ref="triggerRef" />
        <!-- 弹窗 -->
        <PrizeDialog ref="prizeDialog" @handle-confirm="handlePrize" />
    </div>
</template>

<script setup>
import { ref, unref, nextTick, reactive, computed, onMounted, onUnmounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import request from '@/request/index';
import { ElMessage } from 'element-plus';
import { isDayBefore, dateDiff, cloneDeep, format } from '@/commons/utils';
import { setLayout, resetLayout } from '@/hooks/layout';
import PrizeDialog from './prizeDialog.vue';
import ImgUpload from '@/components/ImgUpload.vue';
import defaultImg from '@/assets/imgs/mall/marketing/not-lucky-share.png';
import shareImg from '@/assets/imgs/mall/marketing/share-default.png';
import draggable from 'vuedraggable';

const router = useRouter();
const route = useRoute();

const luckyForm = ref(null);
let buttonRef = reactive([]);
const popoverRef = ref(null);
const position = ref({
    top: 0,
    left: 0,
    bottom: 0,
    right: 0
});
const triggerRef = ref({
    getBoundingClientRect() {
        return position.value;
    }
});
let tooltipVisible = ref(false);
const prizeDialog = ref(null);
const shareImgRef = ref(null);
const defaultImgRef = ref(null);

const luckDrawTurntable = reactive(
    new Array(8).fill({}).map((item, index) => {
        return {
            awardRelation: 1, //奖品和九宫格的关联
            reorder: index, //排序
            weight: null, //权重
            awardProbability: null
        };
    })
);
const form = reactive({
    activityName: '', //活动名称
    activityAt: [], // 开始结束时间
    remark: '', // 抽奖规则
    perPersonNum: null, //每人一共可抽奖
    perPerson: false,
    everyDayNum: 1, //每人每天可抽奖
    award: false,
    awardNum: null, //中奖次数
    extraRaffle: false,
    extraRaffleType: null, //额外抽奖了类型 1 每人 2每天
    extraRaffleNum: null, //额外抽奖次数
    shareCopy: null, //分享文案
    shareImg: 'default', //分享图片
    styleType: 1, // todo:转盘样式到时候去掉
    noLuckyConfig: {
        awardName: '谢谢惠顾',
        awardRelation: 1,
        awardType: 3,
        isDefault: 2,
        sendAwardMethod: 0,
        address: '',
        couponId: 0,
        awardSurplusNum: 1,
        awardImg: 'default' // todo:图片
    }, // 未中奖设置
    luckDrawAward: [],
    luckDrawTurntable: luckDrawTurntable // //转盘设置对象
});
const luckDrawAwardCol = reactive([
    { label: '奖品类型', prop: 'awardType' },
    { label: '奖品名称', prop: 'awardName', showOverflowTooltip: true },
    { label: '奖品数量', prop: 'awardSurplusNum' },
    { label: '剩余数量', prop: 'awardTotalNum' },
    { label: '转盘图片', prop: 'awardImg' },
    { label: '操作', prop: 'operation' }
]);
const turntableCol = reactive([
    { label: '奖品名称', prop: 'awardRelation', showOverflowTooltip: true, minWidth: '240' },
    { label: '转盘图片', prop: 'img', width: '180' },
    { label: '奖品权重', prop: 'weight', width: '200' },
    { label: '转到概率', prop: 'awardProbability', width: '180' }
]);
const defaultTime = [new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 2, 1, 23, 59, 59)];
const disabledDate = date => {
    return isDayBefore(date);
};
const disabledBeforeDate = date => {
    return isDayBefore(date, form.activityAt[0]);
};
let infoDrawAwardIds = reactive([]);
let luckDrawAwardId = reactive([]);
const sortOptions = reactive({
    animation: 150,
    ghostClass: 'sortable-ghost',
    chosenClass: 'sortable-chosen',
    dragClass: 'sortable-drag'
});

const isDisabled = computed(() => {
    const realStatus = route?.query?.realStatus;
    return realStatus == 2;
});

const checkActivityAt = (rule, value, callback) => {
    if (isDisabled.value) {
        if (isDayBefore(value[1], value[0])) {
            return callback('结束时间不能早于开始时间');
        }
        const currentDate = new Date();
        if (value[1] < currentDate) {
            return callback(new Error('结束时间不能早于当前时间'));
        }
        return callback();
    }
    if (!value || !value[0]) {
        return callback(new Error('请选择活动时间'));
    }
    if (value) {
        const currentDate = new Date();
        if (value[0] < currentDate) {
            return callback(new Error('活动时间不能早于当前时间'));
        }
    }
    callback();
};
const checkEveryDayNum = (rule, value, callback) => {
    // todo:规则
    if (!value) {
        return callback(new Error('请填写抽奖次数，次数至少大于0'));
    }
    if (form.perPerson && !form.perPersonNum) {
        return callback(new Error('请填写每人一共可抽奖次数，次数至少大于0'));
    }
    if (form.perPerson && form.perPersonNum < form.everyDayNum) {
        return callback(new Error('每人总抽奖次数需大于等于每天总抽奖次数'));
    }
    callback();
};
const rules = computed(() => {
    const baseRuleList = {
        activityName: [
            { required: true, message: '请输入活动名称', trigger: 'blur' },
            { max: 20, message: '最长不超过20个字', trigger: 'blur' }
        ],
        activityAt: [{ required: true, trigger: 'change', validator: checkActivityAt }],
        remark: [
            { required: false, message: '请输入抽奖规则', trigger: 'blur' },
            { max: 500, message: '最长不超过500个字', trigger: 'blur' }
        ],
        'noLuckyConfig.awardName': [{ required: true, trigger: 'blur', message: '请输入未中奖设置名称' }],
        'noLuckyConfig.awardImg': [{ required: true, trigger: 'change', message: '请选择未中奖设置图片' }],
        everyDayNum: [{ required: true, trigger: 'blur', validator: checkEveryDayNum }],
        shareCopy: [{ required: true, trigger: 'blur', message: '请输入分享文案' }],
        shareImg: [{ required: true, trigger: 'change', message: '请选择分享图片' }]
    };
    return { ...baseRuleList };
});
const weightRules = reactive([{ required: true, message: '请输入奖品权重', trigger: 'blur' }]);

const id = computed(() => {
    return route?.query?.id;
});
const luckyList = computed(() => {
    const luckDrawTurntable = cloneDeep(form.luckDrawTurntable);
    luckDrawTurntable.splice(4, 0, {
        name: '未开始'
    });
    return luckDrawTurntable;
});
const leftList = computed(() => {
    const luckDrawTurntable = cloneDeep(form.luckDrawTurntable);
    return [luckDrawTurntable[2], luckDrawTurntable[3], luckDrawTurntable[4], luckDrawTurntable[5]];
});
const rightList = computed(() => {
    const luckDrawTurntable = cloneDeep(form.luckDrawTurntable);
    return [luckDrawTurntable[1], luckDrawTurntable[0], luckDrawTurntable[7], luckDrawTurntable[6]];
});

const drawSelectList = computed(() => {
    return cloneDeep([...form.luckDrawAward, form.noLuckyConfig]);
});

const getTypeName = type => {
    const types = ['商品', '优惠券'];
    return types[type - 1];
};

const getCurrentImg = (val, imgSrc) => {
    if (val?.[0]?.response?.data?.url) {
        return val?.[0]?.response?.data?.url;
    }
    if (!val) {
        return imgSrc || defaultImg;
    }
    if (val === 'default') {
        return imgSrc || defaultImg;
    }
    return val;
};

const getImgSrcString = img => {
    return img?.[0]?.response?.data?.url || 'default';
};
const getImgSrc = img => {
    return img?.[0]?.response?.data?.url || defaultImg;
};
const getImgSrcObject = img => {
    if (img?.[0]?.response?.data?.url) {
        return img?.[0]?.response?.data?.url;
    }
    if (!img) {
        return defaultImg;
    }
    if (img === 'default') {
        return defaultImg;
    }
    return img;
};
const setImgSrcObject = img => {
    if (img?.[0]?.response?.data?.url) {
        return img?.[0]?.response?.data?.url;
    }
    if (!img) {
        return 'default';
    }
    return img;
};
const getImgSrcForId = id => {
    return getImgSrcObject(drawSelectList.value.find(item => item.awardRelation === id)?.awardImg);
};
const handleDefault = () => {
    if (defaultImgRef.value.loading) {
        return ElMessage({
            type: 'error',
            message: '未中奖设置图片正在上传中...，请稍后恢复默认图'
        });
    }
    form.noLuckyConfig.awardImg = 'default';
};
const skuSpanMethod = ({ row, column, rowIndex, columnIndex }) => {
    if (columnIndex === 0) {
        if (rowIndex === 0) {
            return {
                rowspan: form.goodsSku.length,
                colspan: 1
            };
        } else {
            return {
                rowspan: 0,
                colspan: 0
            };
        }
    } else {
        return {
            rowspan: 1,
            colspan: 1
        };
    }
};

const handlePerPersonNum = val => {
    if (val) {
        form.perPersonNum = 1;
        return;
    }
    form.perPersonNum = null;
};

const handleAwardNumChange = val => {
    if (val) {
        form.awardNum = 1;
        return;
    }
    form.awardNum = null;
};
const handleExtraRaffleChange = val => {
    if (val) {
        form.extraRaffleType = 2;
        form.extraRaffleNum = 10;
        return;
    }
    form.extraRaffleType = null;
    form.extraRaffleNum = null;
};

const handleAwardNumBlur = () => {
    form.awardNum = form.awardNum || 1;
};

const cancelHandler = () => {
    router.back();
};
const clearValidate = field => {
    unref(luckyForm).clearValidate(field);
};

const handleMouseover = e => {
    if (!isDisabled.value) {
        return;
    }
    tooltipVisible.value = true;
    position.value = DOMRect.fromRect({
        width: 0,
        height: 0,
        x: e.clientX,
        y: e.clientY
    });
};
const handleMouseleave = el => {
    if (!isDisabled.value) {
        return;
    }
    tooltipVisible.value = false;
    position.value = {
        top: 0,
        left: 0,
        bottom: 0,
        right: 0
    };
};
// 打开添加编辑奖品窗口
const handlePrizeDialog = row => {
    prizeDialog.value.handleDialog(cloneDeep(row));
};
// 删除
const handleRemove = row => {
    if (infoDrawAwardIds.includes(row.id)) {
        // 记录返回信息里被删除的奖项id
        luckDrawAwardId.push(row.id);
    }
    form.luckDrawAward = form.luckDrawAward.filter(item => item.awardRelation !== row.awardRelation);
    // 如果有转盘使用该奖品，则删除转盘的相关奖品
    form.luckDrawTurntable = form.luckDrawTurntable.map(item => {
        if (item.awardRelation === row.awardRelation) {
            item.awardRelation = 1;
        }
        return item;
    });
};
const getAwardName = id => {
    return drawSelectList?.value?.find(item => item.awardRelation === id)?.awardName;
};
// 确认添加或者编辑奖品
const handlePrize = (query, type) => {
    const _query = cloneDeep(query);
    if (type == 'add') {
        const maxId = Math.max(...drawSelectList.value.map(item => item.awardRelation));
        query.awardRelation = maxId + 1;
        form.luckDrawAward.push(query);
        return;
    }
    const fIndex = form.luckDrawAward.findIndex(item => item.awardRelation == _query.awardRelation);
    form.luckDrawAward[fIndex] = query;
};
// 新增/编辑表单
const saveHandler = async () => {
    if (!unref(luckyForm)) return;
    await unref(luckyForm).validate(async (valid, fields) => {
        if (shareImgRef.value.loading) {
            return ElMessage({
                type: 'error',
                message: '分享图片正在上传中...，请稍后保存'
            });
        }
        if (defaultImgRef.value.loading) {
            return ElMessage({
                type: 'error',
                message: '未中奖设置图片正在上传中...，请稍后保存'
            });
        }
        if (luckDrawTurntable.every(item => item.awardRelation != 1)) {
            return ElMessage({
                type: 'error',
                message: '转盘设置奖品至少设置一个未中奖设置'
            });
        }
        const routerId = unref(id);
        if (valid) {
            const _form = cloneDeep(form);
            // 重新解构组装form
            const {
                id,
                activityName,
                activityAt,
                styleType,
                remark,
                perPersonNum,
                perPerson,
                everyDayNum,
                award,
                awardNum,
                extraRaffle,
                extraRaffleType,
                extraRaffleNum,
                shareCopy,
                shareImg,
                noLuckyConfig,
                luckDrawTurntable,
                luckDrawTurntableId,
                luckDrawAward
            } = _form;
            const [activityStartTime, activityEndTime] = activityAt;
            let query = {
                baseInfo: {
                    activityName,
                    activityStartTime: format(activityStartTime, 'YYYY-MM-DD HH:mm:ss'),
                    activityEndTime: format(activityEndTime, 'YYYY-MM-DD HH:mm:ss'),
                    remark
                },
                luckDrawConfig: {
                    styleType,
                    perPersonNum: perPersonNum || 0,
                    everyDayNum,
                    awardNum,
                    extraRaffleType,
                    extraRaffleNum,
                    shareCopy,
                    shareImg: setImgSrcObject(shareImg)
                },
                luckDrawAward: [...luckDrawAward, noLuckyConfig].map(item => {
                    item.awardImg = setImgSrcObject(item.awardImg);
                    if (item.id && item.awardType != 3) {
                        // id有值是增加的奖品数量 ID无值是需要填充的数量
                        const target = luckDrawAwardCopy.find(lItem => lItem.id == item.id);
                        item.awardSurplusNum = item.awardSurplusNum - (target?.awardSurplusNum || 0);
                    }
                    // 删除不需要的值
                    delete item.awardTotalNum;
                    return item;
                }),
                luckDrawTurntable: luckDrawTurntable.map((item, index) => {
                    item.reorder = index + 1; // 排序
                    item.awardProbability = Math.round(getWeightVal(item.weight) * 100);
                    return item;
                })
            };
            if (routerId) {
                query = { ...query, id, luckDrawTurntableId };
            }
            if (luckDrawAwardId && luckDrawAwardId?.length) {
                query = { ...query, id, luckDrawAwardId };
            }
            const { code } = await request(`activityDraw${routerId ? 'Update' : 'Create'}`, query);
            if (code !== 0) {
                return;
            }
            ElMessage({
                type: 'success',
                message: '抽奖活动保存成功'
            });
            cancelHandler();
        } else {
            unref(luckyForm).scrollToField(Object.keys(fields)?.[0]);
        }
    });
};

const getWeight = val => {
    return `${getWeightVal(val)}%`;
};

const getWeightVal = val => {
    // 计算权重
    if (!val) {
        return 0;
    }
    const finalVal = form.luckDrawTurntable.reduce((prev, cur) => {
        return prev + cur.weight || 0;
    }, 0);
    return (val * (100 / finalVal)).toFixed(2);
};

let luckDrawAwardCopy = reactive({}); // 奖品备份，用于数量计算
const getDetail = async () => {
    // todo:获取抽奖详情
    if (unref(id)) {
        const { data } = await request('activityDrawInfo', { id: unref(id) }); //await request('activityDrawInfo', { id: unref(id) })
        // todo:数据格式化
        const { baseInfo, luckDrawConfig, luckDrawAward, luckDrawTurntable } = data;
        const luckDrawAwardList = luckDrawAward.filter(item => item.awardType !== 3);
        let [noLuckyConfig = form.noLuckyConfig] = luckDrawAward.filter(item => item.awardType === 3);
        luckDrawConfig.perPersonNum = luckDrawConfig.perPersonNum || null;
        luckDrawConfig.perPerson = !!luckDrawConfig.perPersonNum;
        luckDrawConfig.awardNum = luckDrawConfig.awardNum || null;
        luckDrawConfig.award = !!luckDrawConfig.awardNum;
        luckDrawConfig.shareImg = luckDrawConfig.shareImg || 'default';
        luckDrawConfig.extraRaffle = !!(luckDrawConfig.extraRaffleType && luckDrawConfig.extraRaffleNum);
        baseInfo.activityAt = [baseInfo.activityStartTime, baseInfo.activityEndTime];
        Object.assign(
            infoDrawAwardIds,
            luckDrawAwardList.map(item => item.id)
        );
        const luckDrawAwardMap = luckDrawAwardList.map(item => {
            const { awardTotalNum, awardSurplusNum } = item;
            item.awardTotalNum = awardSurplusNum;
            item.awardSurplusNum = awardTotalNum;
            return item;
        });
        luckDrawAwardCopy = cloneDeep(luckDrawAwardMap);
        Object.assign(form, {
            ...baseInfo,
            ...luckDrawConfig,
            noLuckyConfig,
            luckDrawAward: luckDrawAwardMap,
            luckDrawTurntable
        });
    }
};

onMounted(() => {
    getDetail();
    setLayout();
});
onUnmounted(() => {
    resetLayout();
});
</script>

<style lang="scss">
.custom-add-popover-class {
    .el-input-number .el-input__inner {
        text-align: left;
    }
}
.custom-draw-table {
    .cell {
        overflow: inherit;
    }
}
.sku-table {
    margin-top: 16px;
    border: 1px solid #eaeaea;
    tbody tr:first-of-type {
        td:first-of-type {
            border-right: 1px solid #eaeaea;
        }
    }
    .good-preview {
        display: flex;
        align-items: center;
        & > div {
            &:first-of-type {
                margin-right: 8px;
                min-width: 36px;
            }
            &:last-of-type {
                display: flex;
                justify-content: center;
                flex-direction: column;
            }
        }
        h5,
        p {
            margin: 0;
        }
        h5 {
            font-size: 14px;
            font-family: PingFangSC-Regular, PingFang SC;
            font-weight: 400;
            color: #33302d;
        }
        p {
            font-size: 12px;
            font-family: PingFangSC-Regular, PingFang SC;
            font-weight: 400;
            color: #969696;
        }
    }
}
.custom-tooltip-class {
    padding: 10px;
    font-size: 14px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    /* color: #33302d; */
}
</style>
<style lang="scss" scoped>
@mixin background-img($url) {
    background-size: 100% 100%;
    background-position: center center;
    background-repeat: no-repeat;
    background-image: url($url);
}
.marketing_lottery_add {
    position: relative;
    min-height: calc(100vh - 190px);
    .custom-number-small {
        width: 60px;
        margin: 0 4px;
    }
    .box-item-span {
        cursor: default;
        text-align: center;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        width: 60px;
    }
    .custom-tip {
        font-size: 12px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #969696;
    }
    h1 {
        font-size: 14px;
        font-weight: 500;
        position: relative;
        padding-left: 15px;
        margin: 0;
        margin-top: 25px;
        margin-bottom: 16px;
        &::before {
            content: '';
            position: absolute;
            left: 0;
            top: 15%;
            width: 3px;
            height: 70%;
            background-color: var(--el-color-primary);
        }
    }

    .form_content {
        overflow-y: auto;
        max-height: calc(100vh - 210px);
        :deep(.el-card) {
            border: none;
            border-radius: 0;
            box-shadow: none;
            .el-card__header,
            .el-card__body {
                padding-left: 24px;
            }
        }
    }
    .base_card {
        &:not(:last-of-type) {
            margin-bottom: 16px;
        }
        :deep(.el-form-item__content) {
            max-width: 400px;
        }
        .expire-at:deep(.el-form-item__content) {
            max-width: initial;
        }
        .activity-name-item {
            :deep(.el-form-item__content) {
                max-width: 450px;
                min-width: 450px;
            }
        }
        .custom-num-item {
            :deep(.el-form-item__content) {
                max-width: 300px;
            }
        }
        .not-width-item {
            :deep(.el-form-item__label) {
                width: initial !important;
            }
        }
        :deep {
            .img-uploader .img-uploader-icon,
            .has-upload-img {
                width: 80px !important;
                height: 80px !important;
            }
        }
        .draw-custom-col {
            position: relative;
            display: flex;
            min-height: 830px;
            .lucky-preview,
            .lucky-preview-table {
                position: absolute;
                right: 0;
                top: -120px;
                z-index: 20;
            }
            .el-table {
                margin-bottom: 0px;
                margin-right: 450px;
            }
            .custom-table {
                flex: 1;
                margin-bottom: 0px;
                margin-right: 450px;
                border: 1px solid #ddd;
                min-width: 500px;
                overflow-y: auto;
                height: 585px;
            }
            .custom-table-col,
            .custom-table-col-drag {
                display: flex;
                border-bottom: 1px solid #eaeaea;
                min-height: 64px;
                align-items: center;
                min-width: 856px;
                user-select: none;
                & > div {
                    flex: 1;
                    min-width: 200px;
                    &:first-of-type {
                        width: 56px;
                        flex: none;
                        min-width: 56px;
                        text-align: center;
                    }
                }
            }
            .custom-table-col {
                &:first-of-type {
                    height: 48px;
                    background: #f9f9f9;
                    font-size: 14px;
                    font-family: PingFangSC-Medium, PingFang SC;
                    font-weight: 500;
                    color: #33302d;
                }
            }
            .sortable-drag {
                cursor: move;
            }

            .sortable-drag-not {
                cursor: not-allowed;
            }
        }
    }
    .good-form-item {
        :deep(> .el-form-item__content) {
            max-width: 800px;
        }
    }
    .form_content {
        overflow-y: auto;
        max-height: calc(100vh - 210px);
    }

    .custom-el-select {
        width: 75px;
        & + span {
            margin: 0 5px;
        }
    }

    :deep .el-input-number .el-input__inner {
        text-align: left;
    }

    .rule-checkbox {
        &:last-of-type {
            margin-top: 16px;
        }
        .el-checkbox {
            margin-right: 5px;
        }
        :deep(.el-input-number) {
            width: 90px;
            margin-right: 5px;
        }
    }

    .form-footer {
        position: absolute;
        bottom: -64px;
        left: -15px;
        display: flex;
        align-items: center;
        justify-content: center;
        width: calc(100% + 31px);
        height: 70px;
        background-color: #fff;
        z-index: 20;
        box-shadow: 0px 0px 10px 0px rgb(212 212 212 / 50%);
        border-radius: 2px;
        & > div {
            /* margin-left: -160px; */
        }
        .el-button {
            width: 80px;
        }
    }

    .el-button.is-disabled,
    .el-button.is-disabled:hover,
    .el-button.is-disabled:focus {
        color: var(--el-disabled-text-color);
        border-color: var(--el-disabled-bg-color);
        background-color: var(--el-disabled-bg-color);
    }

    .lucky-preview {
        border: 1px solid #eee;
        width: 390px;
        min-width: 390px;
        max-width: 390px;
        height: 844px;
        @include background-img('@/assets/imgs/mall/marketing/lucky_preview_bg.png');
        &-list {
            position: absolute;
            width: 300px;
            height: 320px;
            margin-top: 230px;
            margin-left: 45px;
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            grid-template-rows: repeat(3, 1fr);
            grid-row-gap: 10px;
            grid-column-gap: 10px;
            &-item {
                display: flex;
                flex-direction: column;
                align-items: center;
                justify-content: center;
                @include background-img('@/assets/imgs/mall/marketing/luck-single-bg.png');
                color: #76340b;
                font-size: 12px;
                &:nth-of-type(5) {
                    color: #fff;
                    @include background-img('@/assets/imgs/mall/marketing/luck-btn-bg@2x.png');
                    .default-item-box {
                        height: 60px;
                        display: flex;
                        justify-content: center;
                        align-items: center;
                        font-size: 28px;
                        font-family: PingFangSC-Semibold, PingFang SC;
                        font-weight: 600;
                        color: #ffffff;
                        line-height: 40px;
                        letter-spacing: 3px;
                        text-shadow: 0px 2px 1px #ba0905;
                    }
                }
                .el-image {
                    margin-bottom: 4px;
                }
            }
        }
        &-bottom {
            display: flex;
            justify-content: space-between;
            align-items: center;
            position: absolute;
            width: 370px;
            height: 124px;
            bottom: 50px;
            left: 10px;
            padding: 0 15px;
            padding-top: 10px;
            box-sizing: border-box;
            @include background-img('@/assets/imgs/mall/marketing/luck-share-bg@2x.png');
            & > div {
                &:first-of-type {
                    width: 42px;
                    height: 42px;
                    background: #ffffff;
                    border-radius: 50%;
                    @include background-img('@/assets/imgs/mall/marketing/luck-share-person@2x.png');
                    background-size: 26px 23px;
                }
                &:nth-of-type(2) {
                    font-size: 14px;
                    font-family: PingFangSC-Medium, PingFang SC;
                    font-weight: 500;
                    flex-direction: column;
                    display: flex;
                    color: #ffffff;
                    p {
                        margin: 0;
                    }
                    p:last-of-type {
                        font-size: 13px;
                        font-family: PingFangSC-Regular, PingFang SC;
                        font-weight: 400;
                    }
                }
                &:last-of-type {
                    width: 62px;
                    height: 30px;
                    background: linear-gradient(180deg, #fff1ce 0%, #ffb63c 100%);
                    border-radius: 15px;
                    font-size: 14px;
                    font-family: PingFangSC-Regular, PingFang SC;
                    font-weight: 400;
                    color: #76340b;
                    display: flex;
                    justify-content: center;
                    align-items: center;
                }
            }
        }
    }
    .image-slot {
        width: 100%;
        height: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
        i {
            font-size: 40px;
        }
    }

    .lucky-preview-table {
        border: 1px solid #eee;
        width: 390px;
        min-width: 390px;
        max-width: 390px;
        height: 844px;
        @include background-img('@/assets/imgs/mall/marketing/lucky_preview_table_bg.png');
        &-list {
            width: 280px;
            height: 280px;
            position: relative;
            border-radius: 140px;
            top: 155px;
            left: 54px;
        }
        .left {
            clip: rect(0px 140px 280px 0px);
            position: absolute;
            right: 0;
            width: 140px;
            height: 280px;
            overflow: hidden;
            & > div {
                & > div {
                    transform-origin: center right;
                    transform: translate(-2px, 35px) rotate(22deg);
                    width: 80px;
                    display: flex;
                    flex-direction: column;
                    align-items: center;
                    justify-content: center;
                    font-size: 12px;
                    font-family: PingFangSC-Medium, PingFang SC;
                    font-weight: 500;
                    color: #76340b;
                }
                &:nth-of-type(1) {
                }
                &:nth-of-type(2) {
                    transform: rotate(45deg);
                }
                &:nth-of-type(3) {
                    transform: rotate(90deg);
                }
                &:nth-of-type(4) {
                    transform: rotate(135deg);
                }
            }
        }
        .right {
            clip: rect(0px 140px 280px 0px);
            position: absolute;
            left: 0;
            width: 140px;
            height: 280px;
            overflow: hidden;
            & > div {
                & > div {
                    transform-origin: center right;
                    transform: translate(55px, -0px) rotate(-30deg);
                    width: 80px;
                    display: flex;
                    flex-direction: column;
                    align-items: center;
                    justify-content: center;
                    font-size: 12px;
                }
                &:nth-of-type(1) {
                    transform: rotate(360deg);
                }
                &:nth-of-type(2) {
                    transform: rotate(315deg);
                }
                &:nth-of-type(3) {
                    transform: rotate(270deg);
                }
                &:nth-of-type(4) {
                    transform: rotate(225deg);
                }
            }
        }
        .circle-left,
        .circle-right {
            width: 140px;
            height: 280px;
            position: absolute;
            right: 0;
        }
        .circle-left {
            border-radius: 0 140px 140px 0;
            transform-origin: 0 50%;
        }
        .circle-right {
            border-radius: 140px 0 0 140px;
            transform-origin: 100% 50%;
        }
        &-bottom {
            display: flex;
            justify-content: space-between;
            align-items: center;
            position: absolute;
            width: 370px;
            height: 124px;
            bottom: 60px;
            left: 10px;
            padding: 0 15px;
            padding-top: 10px;
            box-sizing: border-box;
            @include background-img('@/assets/imgs/mall/marketing/luck-share-bg@2x.png');
            & > div {
                &:first-of-type {
                    width: 42px;
                    height: 42px;
                    background: #ffffff;
                    border-radius: 50%;
                    @include background-img('@/assets/imgs/mall/marketing/luck-share-person@2x.png');
                    background-size: 26px 23px;
                }
                &:nth-of-type(2) {
                    font-size: 14px;
                    font-family: PingFangSC-Medium, PingFang SC;
                    font-weight: 500;
                    flex-direction: column;
                    display: flex;
                    color: #ffffff;
                    p {
                        margin: 0;
                    }
                    p:last-of-type {
                        font-size: 13px;
                        font-family: PingFangSC-Regular, PingFang SC;
                        font-weight: 400;
                    }
                }
                &:last-of-type {
                    width: 62px;
                    height: 30px;
                    background: linear-gradient(180deg, #fff1ce 0%, #ffb63c 100%);
                    border-radius: 15px;
                    font-size: 14px;
                    font-family: PingFangSC-Regular, PingFang SC;
                    font-weight: 400;
                    color: #76340b;
                    display: flex;
                    justify-content: center;
                    align-items: center;
                }
            }
        }
    }
}
</style>
